`include "defines.svh"
module DataHazard (
    input logic [31:0]ID_Instr,
    input logic [2:0]ID_Reg_Writed,
    input logic [31:0]EXE_Instr,
    input logic EXE_MemToRegWr,
    input logic [4:0]EXE_RW,
    input logic [31:0] MEM_Instr,
    input logic [4:0] EXE_Rt,
    input logic [4:0] EXE_Rs,
    input logic [4:0]MEM_RW,
    input logic MEM_MemToRegWr,

    output logic [4:0]ID_RW,
    output logic DH_IF_PCWr,
    output logic DH_IF_IDWr,        //这个信号是不是应该没有用了
    output logic ID_EXE_Flush_DH,
    output logic mfc0_DH,
    output logic Side_DH
);
    logic EXE_IsLoad;
    always_comb begin
        if(EXE_Instr[31:26] == `lb || EXE_Instr[31:26] == `lbu || EXE_Instr[31:26] == `lh || EXE_Instr[31:26] == `lhu || EXE_Instr[31:26] == `lw)
            EXE_IsLoad = 1'b1;
        else 
            EXE_IsLoad = 1'b0;
    end

    always_comb begin                                                                          //选择要写入的寄存器
        unique case(ID_Reg_Writed)
        3'b000:
            ID_RW = 5'b00000;
        3'b001:
            ID_RW = 5'b11111;
        3'b010:
            ID_RW = ID_Instr[20:16];
        3'b011:
            ID_RW = ID_Instr[15:11];
        default:
            ID_RW = 5'b00000;
        endcase
    end


    always_comb begin
        if((EXE_Rt==MEM_RW)&&(MEM_Instr[31:26]==`P_type)&&(MEM_Instr[25:21]==`mfc0))begin
            mfc0_DH = 1'b1;
        end
        else if((EXE_Rs==MEM_RW)&&(MEM_Instr[31:26]==`P_type)&&(MEM_Instr[25:21]==`mfc0))begin
            mfc0_DH = 1'b1;
        end else begin
            mfc0_DH = '0;
        end
    end

    always_comb begin
        if(EXE_MemToRegWr && (ID_Instr[25:21] == EXE_RW) && EXE_RW!='0 && EXE_IsLoad)begin  
            DH_IF_IDWr=1'b0;
            DH_IF_PCWr=1'b0;
            ID_EXE_Flush_DH=1'b1;
        end
        else if(EXE_MemToRegWr && (ID_Instr[20:16] == EXE_RW) && EXE_RW!='0 && EXE_IsLoad)begin        //lw+R型指令 阻塞IF_ID,清空ID_EXE
            DH_IF_IDWr=1'b0;
            DH_IF_PCWr=1'b0;
            ID_EXE_Flush_DH=1'b1;
        end 
        else begin
            DH_IF_IDWr=1'b1;
            DH_IF_PCWr=1'b1;
            ID_EXE_Flush_DH=1'b0;
        end
    end
    always_comb begin
        if((ID_Instr[25:21] == MEM_RW) && (MEM_MemToRegWr) && (MEM_RW != '0))    
            Side_DH = 1'b1;
        else if((ID_Instr[20:16] == MEM_RW) && (MEM_MemToRegWr) && (MEM_RW != '0))     
            Side_DH = 1'b1;
        else
            Side_DH = 1'b0;
    end      
endmodule
